package com.yc.boottxx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.boottxx.vo.Result;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("loginedUser") ==null) {
            String accept = request.getHeader("Accept");
            if(accept.startsWith("application/json")) {
                // ajax 方法 => 控制器方法 => 返回json数据
                Result fail = Result.fail("请先登录系统");
                // 设置字符集,不然有乱码
                response.setContentType("application/json;charset=utf-8");
                new ObjectMapper().writeValue(response.getWriter(),fail);
            } else {
                // 获取上细纹路径, 例: demo_txx_war_exploded => contextPath
                String contextPath = request.getContextPath();
                // 点击超链接 或者 表单提交 => 跳转方式
                response.sendRedirect(contextPath + "/login.html");
            }
            return false;
        }
        return true;
    }
}
